﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace App_Code.Helpers
{
    /// <summary>
    /// Summary description for MegaVideoExtractor
    /// </summary>
    public class MegaVideoExtractor
    {
        private const string CONTROL_URI = "http://www.megavideo.com/xml/videolink.php?v={0}";
        private const string VIDEO_URL = "http://www.megavideo.com/?v={0}";
        private const string URL_REGEX = @"megavideo\.com.*?[v,d][=,/](.{8})";
        private const string MEGAUPLOAD_URL_REGEX = @"megaupload\.com.*?d[=,/](.{8})";
        private const string MEGAVIDEO_D_URL = "http://www.megavideo.com/?d={0}";
        private const string PREMIUM_URL = "http://www.megavideo.com/xml/player_login.php?u={0}&v={1}";

        public static string Referer
        {
            get
            {
                return "http://www.megavideo.com/";
            }
        }
        
        public static List<string> GetMovieUrls(string content)
        {
            var movieCodes = new List<string>();
            var exp = new Regex(URL_REGEX, RegexOptions.IgnoreCase);
            var matches = exp.Matches(content);
            foreach (Match match in matches)
            {
                if (match.Success)
                {
                    var movieCode = string.Format(VIDEO_URL, match.Groups[1].Value);
                    if (!movieCodes.Contains(movieCode))
                    {
                        movieCodes.Add(movieCode);
                    }
                }
            }
            return movieCodes;
        }

        public static void CheckVideoLink(string movieUrl)
        {
            var movieCode = new Regex(URL_REGEX, RegexOptions.IgnoreCase).Match(movieUrl).Groups[1].Value;
            var content = Utils.GetPage(string.Format(CONTROL_URI, movieCode), Encoding.Default);
            var match = new Regex("errortext=\"(.+?)\"", RegexOptions.IgnoreCase).Match(content);
            if (match.Success)
                throw new Exception(match.Groups[1].Value);
        }

        public static VideoResult ExtractMovieUrl(string movieUrl)
        {
            if (IsContainMegaUploadVideoLink(movieUrl))
            {
                movieUrl = ConvertToMegaVideoLink(movieUrl);
            }

            CheckVideoLink(movieUrl);

            var premiumCode = Utils.GetMegaVideoPremium();
            if (!string.IsNullOrEmpty(premiumCode))
            {
                var movieCode = new Regex(URL_REGEX, RegexOptions.IgnoreCase).Match(movieUrl).Groups[1].Value;
                var extractUrl = string.Format(PREMIUM_URL, premiumCode, movieCode);
                var content = Utils.GetPage(extractUrl, Encoding.Default);
                var match = Regex.Match(content, "downloadurl=\"(.+?)\"", RegexOptions.IgnoreCase);
                if (match.Success)
                {
                    var videoLink = Utils.LoopDecodeUrl(match.Groups[1].Value);
                    var splitedUrl = videoLink.Split(new[] {"/"}, StringSplitOptions.RemoveEmptyEntries);
                    var videoName = videoLink;
                    if(splitedUrl.Length > 0)
                    {
                        videoName = splitedUrl[splitedUrl.Length-1];
                    }
                    return new VideoResult(videoLink, videoName, true);
                }
            }
            
            return new VideoResult(movieUrl, true);
        }

        public static bool IsContainVideoLink(string url)
        {
            var match = Regex.Match(url, URL_REGEX, RegexOptions.IgnoreCase);
            return match.Success || IsContainMegaUploadVideoLink(url);
        }

        public static bool IsContainMegaUploadVideoLink(string content)
        {
            var match = Regex.Match(content, MEGAUPLOAD_URL_REGEX, RegexOptions.IgnoreCase);
            return match.Success;
        }

        public static string ConvertToMegaVideoLink(string link)
        {
            var match = Regex.Match(link, MEGAUPLOAD_URL_REGEX, RegexOptions.IgnoreCase);
            var megaVideoDLink = string.Format(MEGAVIDEO_D_URL, match.Groups[1].Value);
            var content = Utils.GetPage(megaVideoDLink, Encoding.Default);
            var vLinkMatch = Regex.Match(content, "flashvars.v = \"([^\"]+)\"", RegexOptions.IgnoreCase);
            if (!vLinkMatch.Success) return string.Empty;
            return string.Format(VIDEO_URL, vLinkMatch.Groups[1].Value);
        }
    }
}